﻿#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <ElementPreviewCanvas.h>
#include <QRegularExpression>
#include <QFileDialog>
#include <TreeModel/ElementTreeModel.h>
#include <QQuickWidget>
#include <QSortFilterProxyModel>
#include <QTreeView>
#include <QStandardItemModel>
#include <QToolButton>
#include <ElementGraphicsView.h>
#include <ElementGraphicsCanvas.h>
#include <qpushbutton.h>
#include <QLabel>
#include <QActionGroup>
#include <TreeModel/ElementsReader.h>
#include <Element/ElementBase.h>
#include <TreeModel/ElementTreeItem.h>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , mpSouceTreeModel(new ElementTreeModel(this))
    , mpFilterProxyModel(new QSortFilterProxyModel(this))
{
    ui->setupUi(this);
    ElementsReader reader;
    if(mpSouceTreeModel->readElementsFile(&reader,":/config/privateElements.json"))
    {
        mpFilterProxyModel->setSourceModel(mpSouceTreeModel);
        ui->treeView->setModel(mpFilterProxyModel);
    }
    ui->dockWidgetLeft->setWindowIcon(QIcon{":/icon/Elemets.svg"});
    QGraphicsScene* priewCanvas=new QGraphicsScene(ui->graphicsView);
    ui->graphicsView->setScene(priewCanvas);
    ElementBase* base =new ElementBase((QGraphicsItem *)nullptr);
    base->setShowRect(100,50);
    priewCanvas->addItem(base);
    connect(base,&ElementBase::clicked,this,[this](){
        QList<QGraphicsItem*> elements=ui->graphicsView->items();
        ElementBase* element=new ElementBase(((ElementBase*)elements[0])->ui());
        ElementGraphicsView *view=(ElementGraphicsView *)this->ui->tabWidget->currentWidget();
        QPointF p=view->mapToScene(QPoint(view->width()/2,view->height()/2));
        element->setPos(p);
        element->setShowRect(80,40);
        view->scene()->addItem(element);
    });
    // installEventFilter(priewCanvas);
    this->initActionsGroup();
    this->initUi();
    this->initConnect();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_searchEdit_textChanged(const QString &arg1)
{
    if(mpFilterProxyModel->rowCount()>0){
        mpFilterProxyModel->setFilterRegularExpression(
            QRegularExpression(arg1,QRegularExpression::CaseInsensitiveOption)
        );
        mpFilterProxyModel->setFilterKeyColumn(1);
        QModelIndex index = mpFilterProxyModel->index(0,0);
        if (index.isValid())
        {
            ui->treeView->expand(index);
            ui->treeView->scrollTo(index);

            QItemSelection selection(index, index);
            ui->treeView->selectionModel()->select(selection, QItemSelectionModel::ClearAndSelect);
        }
    }
}


void MainWindow::initActionsGroup()
{
    ui->actionDrag->setCheckable(true);
    ui->actionDrag->setChecked(true);
    ui->actionLabel->setCheckable(true);
    ui->actionLine->setCheckable(true);
    ui->actionLinePoint->setCheckable(true);
    QActionGroup *actionGroup = new QActionGroup(this);
    actionGroup->addAction(ui->actionDrag);
    actionGroup->addAction(ui->actionLabel);
    actionGroup->addAction(ui->actionLine);
    actionGroup->addAction(ui->actionLinePoint);
    actionGroup->addAction(ui->actionHLine);
    actionGroup->addAction(ui->actionVLine);
    connect(actionGroup, &QActionGroup::triggered,this,[this](QAction* action){
            if(action == ui->actionDrag)
            {
                this->mCurrentActionType = ActionType::ActionDrag;
                emit actionTypeChanged(ActionType::ActionDrag);
            }
            else if(action == ui->actionLabel)
            {
                this->mCurrentActionType = ActionType::ActionLabel;
                emit actionTypeChanged(ActionType::ActionLabel);
            }
            else if(action == ui->actionLine)
            {
                this->mCurrentActionType = ActionType::ActionLine;
                emit actionTypeChanged(ActionType::ActionLine);
            }
            else if(action == ui->actionLinePoint)
            {
                this->mCurrentActionType = ActionType::ActionLinePoint;
                emit actionTypeChanged(ActionType::ActionLinePoint);
            }
            else if(action == ui->actionVLine){
                this->mCurrentActionType = ActionType::ActionVLine;
                emit actionTypeChanged(ActionType::ActionVLine);
            }
            else if(action == ui->actionHLine){
                this->mCurrentActionType = ActionType::ActionHLine;
                emit actionTypeChanged(ActionType::ActionHLine);
            }
        });
}

void MainWindow::initStyleSheet()
{
    // ui-> //hover设置鼠标滚动样式 selected设置鼠标选中样式
    ui->treeView->setStyleSheet(".QTreeView::item:hover{background-color:rgb(249, 255, 255)}"\
                                ".QTreeView::item:selected{background-color:rgba(170, 200, 255,0.2)}"
                                // ".QTreeView::branch:closed:has-children{border-image:url();}"
                                // ".QTreeView::branch:open:has-children{border-image:url();}"
                                );
    ui->treeView->setStyleSheet(".QTreeView::item:hover{background-color:rgb(249, 255, 255)}"\
                                ".QTreeView::item:selected{background-color:rgba(170, 200, 255,0.2)}"
                                // ".QTreeView::branch:closed:has-children{border-image:url();}"
                                // ".QTreeView::branch:open:has-children{border-image:url();}"
                                );
}

#include <QGraphicsTextItem>
void MainWindow::initUi()
{
    // 给添加工具栏添加一个QToolButton
    mLayoutToolBt = new QToolButton (ui->toolBarFile);
    mLayoutToolBt->setPopupMode(QToolButton::MenuButtonPopup);
    mLayoutToolBt->setIcon(QIcon("://icon/布局.svg"));
    ui->toolBarFile->insertWidget(ui->actionNewProject,mLayoutToolBt);
    ui->toolBarFile->insertSeparator(ui->actionNewProject);
    mLayoutToolBt->addAction(ui->actionElements);
    mLayoutToolBt->addAction(ui->actionEdit);
    mLayoutToolBt->addAction(ui->actionGridding);
    mLayoutToolBt->addAction(ui->actionVRuler);
    mLayoutToolBt->addAction(ui->actionHRuler);

    on_actionNewProject_triggered();

    initStatusBarUi();
}

#define ElementGraphicsViewFunc(F) [this](bool b)\
{\
    auto* cur = (ElementGraphicsView *)ui->tabWidget->currentWidget();\
    if(cur)\
        cur->F(b);\
}

void MainWindow::initConnect()
{
    QObject::connect(
        ui->actionGridding,
        &QAction::toggled,
        ui->tabWidget,
        ElementGraphicsViewFunc(setGridLine)
        );
    QObject::connect(
        ui->actionHRuler,
        &QAction::toggled,
        ui->tabWidget,
        ElementGraphicsViewFunc(setHorizonRuler)
        );
    QObject::connect(
        ui->actionVRuler,
        &QAction::toggled,
        ui->tabWidget,
        ElementGraphicsViewFunc(setVerticalRuler)
        );


}

void MainWindow::initStatusBarUi()
{
    ui->statusbar->setLeftAction(ui->actionElements);//actionElements
    ui->statusbar->setRightAction(ui->actionEdit);
}

void MainWindow::on_actionElements_triggered(bool)
{
    ui->dockWidgetLeft->setVisible(!ui->dockWidgetLeft->isVisible());
}

void MainWindow::on_actionEdit_triggered(bool)
{
    ui->dockWidgetRight->setVisible(!ui->dockWidgetRight->isVisible());
}

void MainWindow::on_actionZoomIn_triggered()
{
    auto* cur = (ElementGraphicsView *)ui->tabWidget->currentWidget();
    if(cur)
        cur->scaleView(1.1);
}

void MainWindow::on_actionZommOut_triggered()
{
    auto* cur = (ElementGraphicsView *)ui->tabWidget->currentWidget();
    if(cur)
        cur->scaleView(1/1.1);
}

void MainWindow::on_actionNewProject_triggered()
{
    auto* view = ui->tabWidget->addNewTab(mTabIcon);
    connect(view,&ElementGraphicsView::zoom,this,[this](qreal muil){
        ui->statusbar->showMessageOnRight("放大倍数："+QString::number(muil*100)+"%");
    });
}

void MainWindow::on_tabWidget_currentChanged(int index)
{
    auto* view = ui->tabWidget->elementGraphicsView(index);
    if(view)
    {
        ui->statusbar->showMessageOnRight("放大倍数："+QString::number(view->multiple()*100)+"%");
        ui->actionGridding->setChecked(view->isGridLine());
        ui->actionHRuler->setChecked(view->isHorizonRuler());
        ui->actionVRuler->setChecked(view->isVerticalRuler());
    }
}

void MainWindow::on_actionOpenFile_triggered()
{

}


void MainWindow::on_actionArrowLeft_triggered()
{
    ElementGraphicsView * view=(ElementGraphicsView *)ui->tabWidget->currentWidget();
    if(!view)
        return;
    QList<QGraphicsItem *> items=view->scene()->selectedItems();
    for(int i=0;i<items.count();++i){
        ((ElementBase*)items[i])->addRotation(-90);
    }
}


void MainWindow::on_actionArrowRight_triggered()
{
    ElementGraphicsView * view=(ElementGraphicsView *)ui->tabWidget->currentWidget();
    if(!view)
        return;
    QList<QGraphicsItem *> items=view->scene()->selectedItems();
    for(int i=0;i<items.count();++i){
        ((ElementBase*)items[i])->addRotation(90);
    }
}


void MainWindow::on_actionHFlip_triggered()
{
    ElementGraphicsView * view=(ElementGraphicsView *)ui->tabWidget->currentWidget();
    if(!view)
        return;
    QList<QGraphicsItem *> items=view->scene()->selectedItems();
    for(int i=0;i<items.count();++i){
        ((ElementBase*)items[i])->horizontalFlip();
    }
}


void MainWindow::on_actionVFlip_triggered()
{
    ElementGraphicsView * view=(ElementGraphicsView *)ui->tabWidget->currentWidget();
    if(!view)
        return;
    QList<QGraphicsItem *> items=view->scene()->selectedItems();
    for(int i=0;i<items.count();++i){
        ((ElementBase*)items[i])->verticalFlip();
    }
}


void MainWindow::on_treeView_clicked(const QModelIndex &index)
{
    QModelIndex sourceIndex=this->mpFilterProxyModel->mapToSource(index);
    ElementTreeItem* treeItem=(ElementTreeItem*)sourceIndex.internalPointer();
    if(!treeItem||!treeItem->isLeaf()){
        return;
    }
    QList<QGraphicsItem *> items=ui->graphicsView->scene()->items();
    ElementBase* element = ((ElementBase*)items[0]);//graphicsView
    elementUi=(ElementBase::ElementUiBase*)sourceIndex.data(Qt::UserRole).toULongLong();
    element->setUi(elementUi);
}
